package com.wuzhao.resume.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuzhao.resume.common.base.PageFactory;
import com.wuzhao.resume.common.base.Result;
import com.wuzhao.resume.common.base.ResultEnum;
import com.wuzhao.resume.common.util.FileUtils;
import com.wuzhao.resume.entity.ResumeDO;
import com.wuzhao.resume.entity.ResumeFile;
import com.wuzhao.resume.entity.ResumeVO;
import com.wuzhao.resume.service.ResumeFileService;
import com.wuzhao.resume.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.*;


/**
 * @author： M1nG
 * @since： 2020-10-17 17:35:51
 * @description： 简历列表展示控制器
 * @version： 1.0
 */
@Controller
@RequestMapping(value = "/")
public class ResumeController {

    @Autowired()
    public ResumeService resumeService;

    @Autowired
    private ResumeFileService resumeFileService;

    @Value("${upload.file.path}")
    public String basePath;

    @Value("${server.servlet.context-path}")
    public String contextPath;

    @GetMapping("/")
    public String index(Model model) {
        QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("job", "district");
        List<ResumeDO> resumeDOList = resumeService.list(queryWrapper);
        Set<String> jobList = new HashSet<>();
        Set<String> districtList = new HashSet<>();
        for (ResumeDO resumeDO : resumeDOList) {
            if (StringUtils.isNotBlank(resumeDO.getJob())) {
                jobList.add(resumeDO.getJob());
            }
            if (StringUtils.isNotBlank(resumeDO.getDistrict())) {
                districtList.add(resumeDO.getDistrict());
            }
        }
        model.addAttribute("contextPath", contextPath);
        model.addAttribute("jobs", jobList);
        model.addAttribute("districts", districtList);
        return "show";
    }

    @GetMapping("/show")
    public String show(Model model) {
        QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("job", "district");
        List<ResumeDO> resumeDOList = resumeService.list(queryWrapper);
        Set<String> jobList = new HashSet<>();
        Set<String> districtList = new HashSet<>();
        for (ResumeDO resumeDO : resumeDOList) {
            if (StringUtils.isNotBlank(resumeDO.getJob())) {
                jobList.add(resumeDO.getJob());
            }
            if (StringUtils.isNotBlank(resumeDO.getDistrict())) {
                districtList.add(resumeDO.getDistrict());
            }
        }
        model.addAttribute("contextPath", contextPath);
        model.addAttribute("jobs", jobList);
        model.addAttribute("districts", districtList);
        return "show";
    }


    @GetMapping("/edit")
    public String edit(Model model) {
        QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("job", "district");
        List<ResumeDO> resumeDOList = resumeService.list(queryWrapper);
        Set<String> jobList = new HashSet<>();
        Set<String> districtList = new HashSet<>();
        for (ResumeDO resumeDO : resumeDOList) {
            if (StringUtils.isNotBlank(resumeDO.getJob())) {
                jobList.add(resumeDO.getJob());
            }
            if (StringUtils.isNotBlank(resumeDO.getDistrict())) {
                districtList.add(resumeDO.getDistrict());
            }
        }
        model.addAttribute("contextPath", contextPath);
        model.addAttribute("jobs", jobList);
        model.addAttribute("districts", districtList);
        return "edit";
    }

    /**
     * 查询展示
     *
     * @param resumeVO
     * @return
     */
    @PostMapping("/show/list")
    @ResponseBody
    public Result showList(@RequestBody ResumeVO resumeVO) {
        Result result = Result.build(ResultEnum.SUCCESS);
        try {
            QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper();
            if (StringUtils.isNotBlank(resumeVO.getName())) {
                queryWrapper.like("name", resumeVO.getName());
            }
            if (StringUtils.isNotBlank(resumeVO.getDistrict())) {
                queryWrapper.like("district", resumeVO.getDistrict());
            }
            if (StringUtils.isNotBlank(resumeVO.getJob())) {
                queryWrapper.like("job", resumeVO.getJob());
            }
            if (StringUtils.isNotBlank(resumeVO.getMobileNumber())) {
                queryWrapper.like("mobile_number", resumeVO.getMobileNumber());
            }
            queryWrapper.orderByDesc("create_time");
            if ("show".equals(resumeVO.getPageType())) {
                queryWrapper.eq("status", 1);
                queryWrapper.notIn("operation_status", 3);
            }
            Page<ResumeDO> page = resumeService.page(PageFactory.createPageInfo(resumeVO.getCurrent(), resumeVO.getSize()), queryWrapper);
            result.setData(page);
            result.setDraw(resumeVO.getDraw() + 1);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 新增或者更新
     *
     * @param resumeDO
     * @return
     */
    @PostMapping("/edit/insertOrUpdate")
    @ResponseBody
    public Result insertOrUpdate(@RequestBody List<ResumeDO> resumeDO) {
        Result result = null;
        try {
            if (resumeDO.size() > 0) {
                for (ResumeDO resume : resumeDO) {
                    resume.setStatus(1);
                }
                resumeService.saveOrUpdateBatchs(resumeDO);
            } else {
                return Result.error("不能为空");
            }
            result = Result.build(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }


    /**
     * 批量删除简历数据
     *
     * @param idList
     * @return
     */
    @PostMapping("/edit/delete")
    @ResponseBody
    public Result delete(@RequestBody List<Integer> idList) {
        Result result = null;
        try {
            if (idList.size() > 0) {
                for (Integer id : idList) {
                    ResumeDO resume = resumeService.getById(id);
                    if (resume == null) {
                        continue;//找不到简历数据
                    }
                    ResumeFile resumeFile = resumeFileService.getById(resume.getFileId());
                    try {
                        FileUtils.deleteFile(resumeFile);
                        resumeFileService.removeById(resume.getFileId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                resumeService.removeByIdList(idList);
                result = Result.build(ResultEnum.SUCCESS);
            } else {
                return Result.error("不能为空");
            }
            result = Result.build(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 批量标记删除简历文件
     *
     * @param idList 简历数据ID
     * @return
     */
    @PostMapping("/edit/deleteFile")
    @ResponseBody
    public Result deleteResumeFile(@RequestBody List<Integer> idList) {
        Result result = null;
        try {
            if (idList.size() > 0) {
                //resumeFile.setStatus(2); //状态2表示删除
                for (Integer id : idList) {
                    ResumeDO resume = resumeService.getById(id);
                    if (resume == null) {
                        continue;//找不到简历数据
                    }
                    resume.setStatus(2);
                    resumeService.updateByResume(resume);
                }
                result = Result.build(ResultEnum.SUCCESS);
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/edit/upload")
    @ResponseBody
    public Result fileUpload(@RequestParam("files") MultipartFile[] files) {
        Result result = null;
        try {
            if (files.length == 0) {
                result = Result.error("文件不能为空");
                return result;
            }
            StringBuffer data = new StringBuffer();
            data.append("上传成功。\n");
            for (int i = 0; i < files.length; i++) {
                //验证:岗位_姓名_地区的唯一性,如存在则不上传
                Map<String, String> parseMap = FileUtils.parseText(files[i].getOriginalFilename());
                QueryWrapper<ResumeDO> resumeQueryWrapper = new QueryWrapper<>();
                resumeQueryWrapper.eq("name", parseMap.get("name"));
                resumeQueryWrapper.eq("job", parseMap.get("job"));
                resumeQueryWrapper.eq("district", parseMap.get("district"));
                resumeQueryWrapper.eq("mobile_number", parseMap.get("mobileNumber"));
                List<ResumeDO> resumeList = resumeService.list(resumeQueryWrapper);
                if (resumeList.size() > 0) { //查到,跳到上传
                    data.append(parseMap.get("job")).append("_").append(parseMap.get("name")).append("_").append(parseMap.get("district")).append("_").append(parseMap.get("mobileNumber")).append("，该简历数据已经存在。").append("\n");
                    continue;
                }
                Map<String, String> resultMap = FileUtils.upload(files[i], basePath);
                resumeService.SaveOrUpdate(resultMap);
            }
            result = Result.build(ResultEnum.SUCCESS);
            result.setData(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

    /**
     * 根据简历ID下载文件
     *
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/show/download")
    @ResponseBody
    public Result fileDownload(@RequestParam("id") Integer id, HttpServletResponse response) {
        Result result = null;
        try {
            if (id == null) {
                result = Result.error("文件不能为空");
                return result;
            }
            QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            queryWrapper.eq("status", 1); //只查询保存的简历文件
            ResumeDO resumeDO = resumeService.getOne(queryWrapper);
            if (resumeDO == null) {
                result = Result.error("该简历数据不存在");
                return result;
            }
            ResumeFile resumeFile = resumeFileService.getById(resumeDO.getFileId());
            if (resumeFile == null) {
                result = Result.error("该简历没有上传文件");
                return result;
            }
            FileUtils.download(resumeDO, resumeFile, id, response);
            result = Result.build(ResultEnum.SUCCESS);
        } catch (FileNotFoundException e) {
            result = Result.error("文件找不到");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新下载");
        }
        return result;
    }

    /**
     * 根简历ID批量下载文件
     *
     * @param idList
     * @param response
     * @return
     */
    @GetMapping("/show/downloadAll")
    @ResponseBody
    public Result fileDownloadAll(@RequestParam("idList") List<Integer> idList, HttpServletResponse response) {
        Result result = null;
        try {
            if (idList.size() > 0) {
                List<ResumeFile> resumeFileAll = new ArrayList<ResumeFile>();

                QueryWrapper<ResumeDO> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id", idList);
                queryWrapper.eq("status", 1); //只查询保存的简历文件

                List<ResumeDO> resumeList = resumeService.list(queryWrapper);

                for (ResumeDO resumeDO : resumeList) {
                    resumeFileAll.add(resumeFileService.getById(resumeDO.getFileId()));
                }

                if (resumeList.size() != idList.size()) {
                    result = Result.error("该简历数据不存在");
                    return result;
                }
                StringBuffer zipName = new StringBuffer(); //构建zip名称
                zipName.append("外协单位简历(" + resumeList.size() + ")份");

                if (StringUtils.isBlank(zipName.toString())) {
                    zipName.append("外协单位简历合集");
                }
                if (resumeFileAll.size() != resumeList.size()) {
                    result = Result.error("该简历没有上传文件");
                    return result;
                }
                FileUtils.downloadAll(zipName.toString(), resumeFileAll, response);
                result = Result.build(ResultEnum.SUCCESS);
            }
        } catch (FileNotFoundException e) {
            result = Result.error("文件找不到");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新下载");
        }
        return result;
    }

    /**
     * 预览简历
     *
     * @param fileId
     * @return
     */
    @GetMapping("/edit/openUrl")
    @ResponseBody
    public Result openUrlPdf(@RequestParam("fileId") Integer fileId) {
        Result result = Result.build(ResultEnum.SUCCESS);
        try {
            QueryWrapper<ResumeFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", fileId);
            ResumeFile resumeFile = resumeFileService.getOne(queryWrapper);
            if (resumeFile == null) {
                result = Result.error("该简历数据不存在");
                return result;
            }
            result.setData(resumeFile);

        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

}
